// DOM 元素
const newIssueBtn = document.getElementById('newIssueBtn');
const newIssueDialog = document.getElementById('newIssueDialog');
const newIssueForm = document.getElementById('newIssueForm');
const cancelBtn = document.getElementById('cancelBtn');
const issueTableBody = document.getElementById('issueTableBody');

// 修改模态框相关元素
const editIssueDialog = document.getElementById('editIssueDialog');
const editIssueForm = document.getElementById('editIssueForm');
const editCancelBtn = document.getElementById('editCancelBtn');

// 当前正在编辑的问题索引
let currentEditIndex = -1;

// 初始化数据
let issues = [
    {
        title: "用户登录模块快响应速度优化",
        status: "处理中",
        priority: "紧急",
        creator: "zhang.san",
        createTime: "2024-01-05 09:30:00",
        updateTime: "2024-01-08 14:20:15"
    },
    {
        title: "数据库连接池内存泄漏问题",
        status: "待处理",
        priority: "紧急",
        creator: "li.si",
        createTime: "2024-01-06 11:25:30",
        updateTime: "2024-01-06 11:25:30"
    },
    {
        title: "订单系统并发处理优化",
        status: "已解决",
        priority: "紧急",
        creator: "wang.wu",
        createTime: "2024-01-02 15:40:22",
        updateTime: "2024-01-07 16:45:10"
    }
];

// 保存初始数据到localStorage
if (!localStorage.getItem('issues')) {
    localStorage.setItem('issues', JSON.stringify(issues));
} else {
    issues = JSON.parse(localStorage.getItem('issues'));
}

// axios 配置
const axiosInstance = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json'
    }
});

// 打开新建问题对话框
newIssueBtn.addEventListener('click', () => {
    newIssueDialog.showModal();
});

// 关闭新建问题对话框
cancelBtn.addEventListener('click', () => {
    newIssueDialog.close();
    newIssueForm.reset();
});

// 提交新建问题表单
newIssueForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const title = document.getElementById('title').value;
    const status = document.getElementById('status').value;
    const priority = document.getElementById('priority').value;
    const currentTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
    
    const newIssue = {
        title,
        status,
        priority,
        creator: 'zhangsan',
        createTime: currentTime,
        updateTime: currentTime
    };
    
    try {
        const response = await axiosInstance.post('/addIssue', newIssue);
        if (response.status === 200) {
            issues.push(newIssue);
            localStorage.setItem('issues', JSON.stringify(issues));
            renderIssueTable();
            newIssueDialog.close();
            newIssueForm.reset();
            alert('问题创建成功！');
        }
    } catch (error) {
        console.error('创建问题失败:', error);
        alert('创建问题失败，请重试！');
    }
});

// 渲染问题列表
function renderIssueTable() {
    issueTableBody.innerHTML = '';
    
    issues.forEach((issue, index) => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${issue.title}</td>
            <td>${issue.status}</td>
            <td>${issue.priority}</td>
            <td>${issue.creator}</td>
            <td>${issue.createTime}</td>
            <td>${issue.updateTime}</td>
            <td>
                <button class="edit-btn" onclick="editIssue(${index})">修改</button>
                <button class="delete-btn" onclick="deleteIssue(${index})">删除</button>
            </td>
        `;
        issueTableBody.appendChild(tr);
    });
    
    // 更新总数显示
    document.getElementById('totalCount').textContent = issues.length;
}

// 删除问题
function deleteIssue(index) {
    if (confirm('确定要删除这个问题吗？')) {
        issues.splice(index, 1);
        localStorage.setItem('issues', JSON.stringify(issues));
        renderIssueTable();
    }
}

// 编辑问题
function editIssue(index) {
    currentEditIndex = index;
    const issue = issues[index];
    
    // 填充表单数据
    document.getElementById('editTitle').value = issue.title;
    document.getElementById('editStatus').value = issue.status;
    document.getElementById('editPriority').value = issue.priority;
    
    // 显示模态框
    editIssueDialog.showModal();
}

// 关闭修改问题对话框
editCancelBtn.addEventListener('click', () => {
    editIssueDialog.close();
    editIssueForm.reset();
    currentEditIndex = -1;
});

// 提交修改问题表单
editIssueForm.addEventListener('submit', (e) => {
    e.preventDefault();
    
    if (currentEditIndex === -1) return;
    
    const title = document.getElementById('editTitle').value;
    const status = document.getElementById('editStatus').value;
    const priority = document.getElementById('editPriority').value;
    const currentTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
    
    // 更新问题数据
    const issue = issues[currentEditIndex];
    issue.title = title;
    issue.status = status;
    issue.priority = priority;
    issue.updateTime = currentTime;
    
    // 保存到localStorage
    localStorage.setItem('issues', JSON.stringify(issues));
    
    // 重新渲染表格
    renderIssueTable();
    
    // 关闭模态框
    editIssueDialog.close();
    editIssueForm.reset();
    currentEditIndex = -1;
});

// 搜索功能
document.querySelector('.search-btn').addEventListener('click', () => {
    const status = document.getElementById('statusFilter').value;
    const priority = document.getElementById('priorityFilter').value;
    const keyword = document.getElementById('searchKeyword').value;
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    
    // 过滤数据
    const filteredIssues = issues.filter(issue => {
        const matchStatus = !status || issue.status === status;
        const matchPriority = !priority || issue.priority === priority;
        const matchKeyword = !keyword || issue.title.toLowerCase().includes(keyword.toLowerCase());
        const matchDate = (!startDate || issue.createTime >= startDate) && 
                         (!endDate || issue.createTime <= endDate);
        
        return matchStatus && matchPriority && matchKeyword && matchDate;
    });
    
    // 更新显示
    renderFilteredIssues(filteredIssues);
});

// 重置搜索
document.querySelector('.reset-btn').addEventListener('click', () => {
    document.getElementById('statusFilter').value = '';
    document.getElementById('priorityFilter').value = '';
    document.getElementById('searchKeyword').value = '';
    document.getElementById('startDate').value = '';
    document.getElementById('endDate').value = '';
    
    renderIssueTable();
});

function renderFilteredIssues(filteredIssues) {
    issueTableBody.innerHTML = '';
    
    filteredIssues.forEach((issue, index) => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${issue.title}</td>
            <td>${issue.status}</td>
            <td>${issue.priority}</td>
            <td>${issue.creator}</td>
            <td>${issue.createTime}</td>
            <td>${issue.updateTime}</td>
            <td>
                <button class="edit-btn" onclick="editIssue(${index})">修改</button>
                <button class="delete-btn" onclick="deleteIssue(${index})">删除</button>
            </td>
        `;
        issueTableBody.appendChild(tr);
    });
    
    document.getElementById('totalCount').textContent = filteredIssues.length;
}

// 初始化页面
renderIssueTable(); 